<?php
/**
 * This file handles the granular control of SEO for
 * the framework.
 *
 * It handles <title> tag generation, meta keywords/descriptions,
 * and the <link rel="canonical"> tag.
 *
 * If either Headspace2 or All-in-One SEO Pack are active,
 * they will be given priority over the framework SEO.
 *
 * @author Nathan Rice
 * @package Prodigy
 **/


/**
 * This function does 3 things:
 * 1. Pulls the values for $sep and $seplocation, uses defaults if necessary
 * 2. Determines if the site title should be appended
 * 3. Allows the user to set a custom title on a per-page/post basis
 *
 * @since 0.1
 */
add_action('prodigy_title', 'wp_title');
add_filter('wp_title', 'prodigy_default_title', 10, 3);
function prodigy_default_title($title, $sep, $seplocation) {
	$sep = (prodigy_option('doctitle_sep')) ? prodigy_option('doctitle_sep') : '&mdash;';
	$seplocation = (prodigy_option('doctitle_seplocation')) ? prodigy_option('doctitle_seplocation') : 'right';
	
	//	if viewing the homepage
	if(is_home()) {
		// make $title = site name
		$title = get_bloginfo('name');
		
		// append site description, if necessary
		$title = (prodigy_option('append_description_home')) ? $title." $sep ".get_bloginfo('description') : $title;
	}
	
	if(is_singular()) {
		//	All-in-One SEO Pack Title (vestigial)
		if(get_custom_field('title',FALSE)) {
			$title = get_custom_field('title',FALSE);
		}
		//	Headspace Title (vestigial)	
		elseif(get_custom_field('_headspace_page_title',FALSE)) {
			$title = get_custom_field('_headspace_title',FALSE);
		}
		//	The User Defined Title
		elseif(get_custom_field('_prodigy_title',FALSE)) {
			$title = get_custom_field('_prodigy_title',FALSE);
		}
	}
	
	//	if we don't want site name appended, or if we're on the homepage
	if(prodigy_option('append_site_title') == FALSE || is_home()) 
		return $title;
	
	// else
	return ($seplocation == 'right') ? $title." $sep ".get_bloginfo('name') : get_bloginfo('name')." $sep ".$title;
}

/**
 * This function generates <code>meta</code> code for SEO.
 * It generates a description and keywords.
 *
 * @since 0.1
 */
add_action('prodigy_meta','prodigy_seo_meta');
function prodigy_seo_meta() {
	global $post;
	
/*
	the description will be made from either (in order of priority)
	1. site description (tagline) if on home page
	2. All-in-One SEO or Headspace2 Description (vestigial)
	3. '_prodigy_description' hidden custom field
	4. the manual excerpt, written by the user
*/
	
	// if we're on the homepage
	if(is_home()) {
		$description = (prodigy_option('home_description')) ? prodigy_option('home_description') : get_bloginfo('description');
	}
	// else if the user used All-in-One SEO Pack (vestigial)
	elseif(get_custom_field('description',FALSE)) {
		$description = get_custom_field('description',FALSE);
	}
	// else if the user used Headspace2 (vestigial)
	elseif(get_custom_field('_headspace_description',FALSE)) {
		$description = get_custom_field('_headspace_description',FALSE);
	}
	// else if description is set via custom field
	elseif(get_custom_field('_prodigy_description',FALSE)) {
		$description = get_custom_field('_prodigy_description',FALSE);
	}
	// else if there is a manual post excerpt
	elseif($post->post_excerpt) {
		$description = $post->post_excerpt;
	}
	// if all else fails, leave description blank
	else {
		//$post_content = strip_shortcodes(strip_tags($post->post_content));
		//$description = (strlen($post_content) <= 150) ? $post_content : substr($post_content,0,150);
		$description = null;
	}
	
	// Add the description, but only if one exists, and where applicable
	if(is_home() || is_single() || is_page()) {
		if(!empty($description))
		echo '<meta name="description" content="'.wp_specialchars($description).'" />'."\n";
	}
	
/*
	the keyword list will be made from either (in order of priority)
	1. Site keywords, set by user in theme options
	2. All-in-One SEO Keywords (vestigial)
	3. '_prodigy_keywords' hidden custom field
	4. the post tags, set by the user
*/
	
	// if we're on the homepage
	if(is_home()) {
		$keywords = prodigy_option('home_keywords');
	}
	// else if keywords are set via All-in-One SEO Pack
	elseif(get_custom_field('keywords',FALSE)) {
		$keywords = get_custom_field('keywords',FALSE);
	}
	// else if keywords are set via custom field
	elseif(get_custom_field('_prodigy_keywords',FALSE)) {
		$keywords = get_custom_field('_prodigy_keywords',FALSE);
	}
	// if all else fails, use the post tags
	else {
		foreach((array)get_the_tags($post->ID) as $tag) { $post_tags .= ','. $tag->name; }
		$keywords = substr($post_tags,1); //removing the first "," from the list
	}
	
	// Add the keywords, but only where applicable
	if(is_home() || is_singular()) {
		if(!empty($keywords))
		echo '<meta name="keywords" content="'.wp_specialchars($keywords).'" />'."\n";
	}
}

/**
 * This function generates the index/follow code in the document <head>
 *
 * @uses prodigy_option, get_custom_field
 *
 * @since 0.1
 */
add_action('prodigy_meta','prodigy_index_follow_logic');
function prodigy_index_follow_logic() {
	global $post;
	
	// if the user wants the blog private, then follow logic
	// is unnecessary. WP will insert noindex and nofollow
	if(get_option('blog_public') == 0) return;
	
	// defaults
	$index = 'index'; $follow = 'follow';
	
	// noindex all archives
	if(is_archive() || is_search())
		$index = 'noindex';
	// ... unless ...
	if(is_category() && prodigy_option('index_cat_archive'))
		$index = 'index';
	if(is_tag() && prodigy_option('index_tag_archive'))
		$index = 'index';
	if(is_author() && prodigy_option('index_author_archive'))
		$index = 'index';
	if(is_date() && prodigy_option('index_date_archive'))
		$index = 'index';
	if(is_search() && prodigy_option('index_search_archive'))
		$index = 'index';
	
	// noindex pages/posts that are specified to noindex
	if(is_singular() && get_custom_field('_prodigy_noindex', FALSE))
		$index = 'noindex';
	
	// nofollow posts/pages that are specified to nofollow
	if(is_singular() && get_custom_field('_prodigy_nofollow', FALSE))
		$follow = 'nofollow';
	
	echo '<meta name="robots" content="'.$index.','.$follow.'" />'."\n";
}

/**
 * This function adds the canonical tag for SEO, unless disabled
 * by the user in the theme settings, or in the in-post SEO settings.
 *
 * @uses prodigy_option, get_custom_field
 *
 * @since 0.1
 */
add_action('prodigy_meta','prodigy_canonical');
function prodigy_canonical() {
	if(prodigy_option('disable_canonical'))
		return;
	if(is_singular() && get_custom_field('_prodigy_disable_canonical', FALSE))
		return;
	
	if(is_singular())
	echo "\n".'<!--The Canonical Tag-->'."\n".'<link rel="canonical" href="' . get_permalink() . '" />'."\n";
}

/**
 * This next section adds a new box to the post/page edit screen,
 * so that the user can set SEO options on a per-post/page basis.
 *
 * prodigy_add_inpost_seo_box() is used to register the boxes.
 * @uses add_meta_box
 * prodigy_inpost_seo_box() generates the content in the boxes.
 * @uses wp_create_nonce, checked, get_custom_field
 *
 * @since 0.1
 */
add_action('admin_menu', 'prodigy_add_inpost_seo_box');
function prodigy_add_inpost_seo_box() {
	add_meta_box('prodigy_inpost_seo_box', __('SEO Options and Settings', 'prodigy'), 'prodigy_inpost_seo_box', 'post', 'advanced', 'high');
	add_meta_box('prodigy_inpost_seo_box', __('SEO Options and Settings', 'prodigy'), 'prodigy_inpost_seo_box', 'page', 'advanced', 'high');
}
function prodigy_inpost_seo_box() { ?>
	
	<input type="hidden" name="prodigy_inpost_seo_nonce" value="<?php echo wp_create_nonce(plugin_basename(__FILE__)); ?>" />
	
	<p><label for="prodigy_title"><b>Custom Document Title</b> (<code>&lt;title&gt;</code> Tag):</label></p>
	<p><input style="width: 99%;" type="text" name="prodigy_seo[_prodigy_title]" id="prodigy_title" value="<?php get_custom_field('_prodigy_title'); ?>" /></p>
	
	<p><label for="prodigy_description"><b>Custom Post/Page Meta Description</b> (<code>&lt;meta name="description"&gt;</code>):</label></p>
	<p><textarea style="width: 99%;" name="prodigy_seo[_prodigy_description]" id="prodigy_description"><?php get_custom_field('_prodigy_description'); ?></textarea></p>
	
	<p><label for="prodigy_keywords"><b>Custom Post/Page Meta Keywords</b> (<code>&lt;meta name="keywords"&gt;</code>, comma separated):</label></p>
	<p><input style="width: 99%;" type="text" name="prodigy_seo[_prodigy_keywords]" id="prodigy_keywords" value="<?php get_custom_field('_prodigy_keywords'); ?>" /></p>
	
	<br />
	
	<p><b>Noindex this Post/Page</b> ( <a href="http://www.robotstxt.org/meta.html" target="_blank">more info</a> )</p>
	<p><input type="checkbox" name="prodigy_seo[_prodigy_noindex]" id="prodigy_noindex" value="1" <?php checked(1, get_custom_field('_prodigy_noindex', FALSE)); ?> /> 
	<label for="prodigy_noindex">Apply <code>noindex</code> to this post/page?</label></p>
	
	<br />
	
	<p><b>Nofollow this Post/Page</b> ( <a href="http://www.robotstxt.org/meta.html" target="_blank">more info</a> )</p>
	<p><input type="checkbox" name="prodigy_seo[_prodigy_nofollow]" id="prodigy_nofollow" value="1" <?php checked(1, get_custom_field('_prodigy_nofollow', FALSE)); ?> /> 
	<label for="prodigy_nofollow">Apply <code>nofollow</code> to this post/page?</label></p>
	
<?php if(!prodigy_option('disable_canonical')) : ?>
	<br />
	<p><b>Remove canonical tag</b> ( <a href="http://www.mattcutts.com/blog/canonical-link-tag/" target="_blank">more info</a> )</p>
	<p><input type="checkbox" name="prodigy_seo[_prodigy_disable_canonical]" id="prodigy_disable_canonical" value="1" <?php checked(1, get_custom_field('_prodigy_disable_canonical', FALSE)); ?> /> 
	<label for="prodigy_disable_canonical">Disable the <code>&lt;link rel="canonical" /&gt;</code> tag for this post/page?</label>
<?php endif;
}

/**
 * This function saves the SEO settings when we save a post/page.
 * It does so by grabbing the array passed in $_POST, looping through
 * it, and saving each key/value pair as a custom field.
 *
 * @uses wp_verify_nonce, plugin_basename, current_user_can
 * @uses add_post_meta, update_post_meta, delete_post_meta, get_custom_field
 *
 * @since 0.1
 */
add_action('save_post', 'prodigy_inpost_seo_save', 1, 2);
function prodigy_inpost_seo_save($post_id, $post) {
	
	//	verify the nonce
	if (!wp_verify_nonce($_POST['prodigy_inpost_seo_nonce'], plugin_basename(__FILE__)))
		return $post->ID;

	//	is the user allowed to edit the post or page?
	if(('page' == $_POST['post_type'] && !current_user_can('edit_page', $post->ID)) || !current_user_can('edit_post', $post->ID ))
		return $post->ID;
		
	$prodigy_seo = $_POST['prodigy_seo'];
		
	//	gotta set these manually, unfortunately, since they're checkboxes
	$prodigy_seo['_prodigy_noindex'] = $_POST['prodigy_seo']['_prodigy_noindex'];
	$prodigy_seo['_prodigy_nofollow'] = $_POST['prodigy_seo']['_prodigy_nofollow'];
	$prodigy_seo['_prodigy_disable_canonical'] = $_POST['prodigy_seo']['_prodigy_disable_canonical'];
	
	//	store the custom fields
	foreach ($prodigy_seo as $key => $value) {
		if($post->post_type == 'revision') return; // don't store data twice
		
		//	sanitize the title, description, and tags before storage
		if($key == '_prodigy_title' || $key == '_prodigy_description' || $key == '_prodigy_keywords')
			$value = esc_html(strip_tags($value));
		
		//	save/update
		if(!get_custom_field($key)) update_post_meta($post->ID, $key, $value);
		else add_post_meta($post->ID, $key, $value, TRUE);
		
		//delete if blank
		if(!$value) delete_post_meta($post->ID, $key);
	}
}

/**
 * Disable all SEO functions if the All-in-One SEO Pack or Headspace is active
 *
 * @since 0.1
 */
if (class_exists('All_in_One_SEO_Pack') || class_exists('HeadSpace2_Plugin')) {
	remove_filter('wp_title', 'prodigy_default_title');
	remove_action('prodigy_meta','prodigy_seo_meta');
	remove_action('prodigy_meta','prodigy_follow_logic');
	remove_action('prodigy_meta','prodigy_canonical');
}

/**
 * disable Prodigy <title> generation if SEO Title Tag is active
 *
 * @since 0.1
 */
if (function_exists('seo_title_tag')) {
	remove_filter('wp_title', 'prodigy_default_title');
}
?>